const { add, find, del, update, updateMany } = require('../model/positionModel')
const moment = require('moment');
//增
const positionAdd = async (req, res) => {
    //get 获取参数 req.query
    //post 获取参数  req.body
    //通过三方的插件来处理createTime
    const time = moment().format("YYYY-MM-DD,hh:mm:ss a")
    req.body.createTime = time;
    //首先获取数据里的数据
    const arr = await find({ field: {} })
    const tokenId = arr.length + 1;
    req.body.tokenId = tokenId;
    console.log(tokenId)
    const result = await add(req.body)
    console.log(result)
    if (result) {
        res.send({ status: true, msg: "保存成功" });
    } else {
        res.send({ status: false, msg: "保存失败" })
    }
}

//删

const positionDel = async (req, res) => {
    console.log("进来了")
    //获取动态路由的值 req.params
    // console.log(req.params)
    const tokenId = parseInt(req.params.id);
    console.log("tokenId是" + tokenId)
    const result = await del(tokenId);
    console.log(result)
    const updateToken = await updateMany(tokenId)
    if (result.n) {
        res.send({ status: true, msg: "删除成功" })
    } else {
        res.send({ status: false, msg: "删除失败" })
    }
}

//改

const positionUpdate = async (req, res) => {
    const { tokenId } = req.body;
    const updates = req.body
    let query = { tokenId: parseInt(tokenId) }
    const result = await update(query, updates)

    if (result) {
        res.send({ status: true, msg: "更新成功" })
    } else {
        res.send({ status: false, msg: "更新失败" })
    }
}


//查找
const positionGetList = async (req, res) => {
    //前端传递过来参数
    //1.page 2.count 3.key
    //page-1*count 公式
    let counts = req.query.count || 4;

    //处理field字段
    //1.用户传了一个id过来 返回当前id对应的数据
    //2.用户点击搜索的时候 传递一个关键字 需要使用正则进行数据库匹配再返回
    //3.用户什么都没传
    let field = "";
    //加入前端同事传了两个值 告诉前端出错
    //可以满足同时传递两个参数
    if (req.query.tokenId && req.query.key) {
        res.send({ status: false, msg: "不要同时传两个参数" })
        return
    }

    if (req.query.tokenId) {
        field = { tokenId: req.query.tokenId }
    } else if (req.query.key) {
        field = { companyName: new RegExp(req.query.key) }
    } else {
        field = {}
    }

    const query = {
        page: (req.query.page - 1) * counts,//前端传递的页码
        count: counts - 0,//一次返回多少条数据
        field: field
    }

    const result = await find(query)
    //因为返回来的是数组 所以可以使用数组的方法
    const count = result.length
    if (result) {
        res.send({ status: true, count: count, list: result })
    } else {
        res.send({ status: false, msg: "获取信息出错" })
    }
}


module.exports = {
    positionAdd,
    positionGetList,
    positionDel,
    positionUpdate
}